package com.yanzhang.servlet;

import com.yanzhang.pojo.User;
import com.yanzhang.service.user.UserService;
import com.yanzhang.service.user.UserServiceImpl;
import com.yanzhang.util.Constants;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;

/**
 * 登录和注销
 * @author yanzhang
 */
public class LoginServlet extends HttpServlet {

    private UserService userService;

    public LoginServlet () {
        userService = new UserServiceImpl();
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String type = req.getParameter("type");
        switch (type) {
            //登录
            case "login": {
                login(req, resp);
                break;
            }
            //注销
            case "logout": {
                logout(req, resp);
                break;
            }
            default: {
                resp.sendRedirect(req.getContextPath() + "/error.jsp");
            }
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }

    /**
     * 登录
     * @param req
     * @param resp
     * @throws IOException
     * @throws ServletException
     */
    private void login (HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
        //获取前端传入的用户名和密码
        String userCode = req.getParameter("userCode");
        String userPassword = req.getParameter("userPassword");
        //与数据库中的用户名和密码对比
        User user = userService.login(userCode, userPassword);
        if (user != null) {
            //将用户存放到Session中
            req.getSession().setAttribute(Constants.USER_SESSION, user);
            //登录成功，跳转到主页
            resp.sendRedirect("jsp/frame.jsp");
        } else {
            System.out.println("用户为空");
            //登录失败，转发到登录页面，顺便带上提示
            req.setAttribute("error", "用户名和密码不正确");
            req.getRequestDispatcher("login.jsp").forward(req, resp);
        }
    }

    /**
     * 注销
     * @param req
     * @param resp
     * @throws IOException
     * @throws ServletException
     */
    private void logout (HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
        req.getSession().removeAttribute(Constants.USER_SESSION);
        resp.sendRedirect(req.getContextPath()+"/login.jsp");
    }
}
